<template>
  <div class="chart-container">
    <!-- ECharts 图表容器 -->
    <div ref="dailyAmountChart" style="width: 100%; height: 500px"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
export default {
  name: 'DailyAmountChart',
  data() {
    return {
      chartInstance: null
    };
  },
  mounted() {
    this.initChart();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
  },
  methods: {
    data() {
      return {
        chartInstance: null,
        chartData: { daily: null, monthly: null }, // 存储两种模式数据
        currentMode: 'daily' // 当前显示模式
      };
    },

    // 初始化图表
    async initChart() {
      try {
        // 1. 获取后端数据
        const response = await axios.get('manage/purchaseOrder/list2');
        const orders = response.data.data; // 假设返回数据结构为AjaxResult标准格式
        console.log( response.data.data+"+++++++++")

        // 2. 数据预处理：按日期聚合金额
        const dailyData = this.processData(orders);

        // 3. 初始化ECharts实例
        this.chartInstance = echarts.init(this.$refs.dailyAmountChart);

        // 4. 配置图表选项
        const option = {
          title: {
            text: '采购订单每日金额统计',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            formatter: '{b}<br/>¥{c}'
          },
          xAxis: {
            type: 'category',
            data: dailyData.dates,
            axisLabel: {
              rotate: 45
            }
          },
          yAxis: {
            type: 'value',
            axisLabel: {
              formatter: '¥{value}'
            }
          },
          series: [{
            data: dailyData.amounts,
            type: 'bar',
            itemStyle: {
              color: '#5470c6'
            }
          }]
        };

        // 5. 渲染图表
        this.chartInstance.setOption(option);
      } catch (error) {
        console.error('数据获取或图表渲染失败:', error);
      }
    },

    // 数据处理方法
    processData(orders) {
      const dateMap = new Map();

      orders.forEach(order => {
        const date = order.approvalTime.split('T')[0]; // 提取日期部分
        const amount = order.totalPrice || 0;

        if (dateMap.has(date)) {
          dateMap.set(date, dateMap.get(date) + amount);
        } else {
          dateMap.set(date, amount);
        }
      });

      // 转换为排序后的数组
      const sortedDates = [...dateMap.keys()].sort();
      return {
        dates: sortedDates,
        amounts: sortedDates.map(date => dateMap.get(date))
      };
    },

    // 窗口大小变化处理
    handleResize() {
      if (this.chartInstance) {
        this.chartInstance.resize();
      }
    }
  }
};
</script>

<style scoped>
.chart-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}
</style>
